import os

import numpy as np

def voice_devide(pcm_path, sound_num, ch_index_to_extract):
    '''
       多声道分离转化,pcm_path为文件路径，sound_num为声道数
       invalid_num为无效声道数（用于消除回声），没有则为0
       fs为采样频率，data_type为数据位数（8位，16位，32位）
      '''
    # 多声道分离,fs为采样频率，data_type为数据位数（8位，16位，32位）
    # pcm_path = 'mic_demo_vvui_ori.audio'
    with open(pcm_path, 'rb') as f:
        audioData = np.fromfile(f, dtype=np.uint16)
    audioData.shape = -1, sound_num  # 有sound_num个声道，即排成sound_num列,一行即为一帧（采样一次）
    # 将各个声道分离，有几个声道复制几次这里，此处只列了6个通道
    audioData = audioData.T
    # 提取指定声道
    channel = audioData[ch_index_to_extract]
    return channel

def split_all(path, ch_num_to_extract ):
    for filepath, dirnames, filenames in os.walk(path):
        for filename in filenames:
            if not filename.endswith(".audio"):
                continue
            print(os.path.join(filepath,filename))
            full_name = os.path.join(filepath, filename)
            ch = voice_devide(full_name, 14, ch_num_to_extract - 1)
            single_ch_file = full_name[:-4] + "_" + str(ch_num_to_extract) + ".audio"
            print(single_ch_file)
            ch.tofile(single_ch_file)

if __name__ == '__main__':
    split_all("D:/试用期/语音套件/声音复刻/测试资源/2.04.0测试集/s3_5002/", 2)